package com.wang.test.demo.dom4j;

import com.wang.test.demo.entity.Book;
import com.wang.test.demo.entity.Student;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;



public class Dom4j {

    private List<Book> bookList = null;
    private Book book = null;

    public List<Book> getBooks(FileInputStream file){

        SAXReader reader = new SAXReader();
        try {

            InputStreamReader iStreamReader= new InputStreamReader(file, "GBK");
            Document document = reader.read(iStreamReader,"GBK"); // 读取XML文件,获得document对象
            Element bookstore = document.getRootElement();
            Iterator storeit = bookstore.elementIterator();

            bookList = new ArrayList<Book>();
            while(storeit.hasNext()){

                book = new Book();
                Element bookElement = (Element) storeit.next();
                //遍历bookElement的属性
                List<Attribute> attributes = bookElement.attributes();
                for(Attribute attribute : attributes){
                    if(attribute.getName().equals("id")){
                        String id = attribute.getValue();//System.out.println(id);
                        book.setId(id);
                    }
                }

                Iterator bookit = bookElement.elementIterator();
                while(bookit.hasNext()){
                    Element child = (Element) bookit.next();
                    String nodeName = child.getName();
                    if(nodeName.equals("name")){
                        //System.out.println(child.getStringValue());
                        String name = child.getStringValue();
                        book.setName(name);
                    }else if(nodeName.equals("author")){
                        String author = child.getStringValue();
                        book.setAuthor(author);
                    }else if(nodeName.equals("year")){
                        String year = child.getStringValue();
                        //book.setYear(Integer.parseInt(year));
                    }else if(nodeName.equals("price")){
                        String price = child.getStringValue();
                        book.setPrice(Double.parseDouble(price));
                    }
                }
                bookList.add(book);
                book = null;

            }
        } catch (DocumentException e) {

            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return bookList;

    }


    /**
     * @param args
     */
//    public static void main(String[] args) throws FileNotFoundException {
//        // TODO Auto-generated method stub
//        //File file = new File();
//        FileInputStream file = new FileInputStream("E:\\template\\test.xml");
//        List<Book> bookList = new Dom4j().getBooks(file);
//        for(Book book : bookList){
//            System.out.println(book);
//        }
//    }

    /**
     * 用DOM4J解析xml文件,并映射到实体类中
     *
     */
    public static void main(String[] args) throws Exception {
        analysis();
    }

    public static void analysis(){
        // 把要解析的xml变成file文件
        File file = new File("E:\\student.xml");

        // 获取解析器对象
        SAXReader reader = new SAXReader();
        // 把文件解析成document树
        Document document = null;
        try {
            document = reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 获取根节点
        Element studentRoot = document.getRootElement();
        // 获取根节点中所有节点
        List<Element> elements = studentRoot.elements();

        // 存放xml中节点的数据集合
        List<Student> list = new ArrayList<>();

        System.out.println("未知属性名+未知子元素名 --> 结果如下");
        // 便利所有节点
        for (Element child : elements) {

            Student student = new Student();

            //已知属性名情况下
            student.setId(child.attributeValue("id"));//获取属性的数据
            //已知子元素名的情况下
            student.setName(child.elementText("name"));//获取元素中值
            student.setAge(Integer.parseInt(child.elementText("age")));//获取元素中值

            list.add(student);

            //未知属性名情况下
            List<Attribute> attributes = child.attributes();
            for (Attribute attribute : attributes) {

                System.out.println(attribute.getName() + "---> " + attribute.getValue());

            }

            //未知子元素名情况下
            List<Element> elementList = child.elements();
            for (Element ele : elementList) {

                System.out.println(ele.getName() + "--->" + ele.getText());

            }
        }
        System.out.println("已知属性名+未知子元素名 --> 结果如下");
        //把解析xml出来的数据集合打印
        list.forEach(x-> System.out.println(x));

    }

}